<script setup>
import { onMounted, ref, watch } from 'vue'
import { queryPageApi, addEmpApi, getEmpByIdApi, updateEmpByIdApi, deleteEmpByIdsApi } from '@/api/emps'
import { queryAllApi } from '@/api/dept'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 头部form变量定义
const formInline = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})

const empData = ref([])

// page分页变量定义
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const size = 'defalut'
const disabled = false
const background = true

// dialog对话框变量定义
const dialogFormVisible = ref(false)
const dialogTitle = ref('')
const empForm = ref({
  username: '',
  name: '',
  gender: null,
  phone: '',
  job: null,
  salary: 0,
  deptId: null,
  entryDate: null,
  image: null,
  exprList: []
})
const genderOptions = ref([
  { gender: '男', value: '1' },
  { gender: '女', value: '2' }
])
const jobOptions = ref([
  { job: '班主任', value: '1' },
  { job: '讲师', value: '2' },
  { job: '部门主管', value: '3' },
  { job: '教研主管', value: '4' },
  { job: '咨询师', value: '5' }
])
const deptOptions = ref([])
// const formLabelWidth = '140px'

const ruleEmpForm = ref(null)

const token = ref({token: ''})


// 文件上传携带token
const imageLoad = () => {
  let loginInfo = localStorage.getItem('loginUser')
  if (loginUser) {
    token.value.token = JSON.parse(loginInfo).token
  }
}

// 监听
watch(() => formInline.value.date, async (newValue) => {
  if (newValue.length == 2) {
    formInline.value.begin = newValue[0]
    formInline.value.end = newValue[1]
  } else {
    formInline.value.begin = ''
    formInline.value.end = ''
  }
})
// 深度监听
// {deep: true}

// 编辑按钮
const handleEdit = async (id) => {
  dialogTitle.value = '编辑员工'
  const result = await getEmpByIdApi(id)
  empForm.value = result.data
  let exprList = empForm.value.exprList
  if (exprList && exprList.length > 0) {
    exprList.forEach((item) => {
      /* item.date = []
      item.date.push(item.begin)
      item.date.push(item.end) */
      item.date = [item.begin, item.end]
    })
  }

  dialogFormVisible.value = true
}


// 删除按钮
const handleDelete = async (id) => {
  ids.value = id
  await deleteIds()
}

// 分页查询
const query = async () => {
  const result = await queryPageApi(formInline.value.name, formInline.value.gender, formInline.value.begin, formInline.value.end, currentPage.value, pageSize.value)
  empData.value = result.data.rows
  total.value = result.data.total
}

// 清空按钮
const clear = () => {
  formInline.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  }
  query()
}

onMounted(async () => {
  query()
  const result = await queryAllApi()
  if (result.code) {
    deptOptions.value = result.data
  }
  imageLoad()
})

// 每页条数发生变化执行
const handleSizeChange = async (val) => {
  currentPage.value = 1
  pageSize.value = val
  query()
}

// 当前页发生变化执行
const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}

// 添加员工按钮
const add = async () => {
  empForm.value = {
    username: '',
    name: '',
    gender: null,
    phone: '',
    job: null,
    salary: 0,
    deptId: null,
    entryDate: null,
    image: null,
    exprList: []
  }
  dialogTitle.value = '新增员工'
  dialogFormVisible.value = true
  if (ruleEmpForm.value) {
    ruleEmpForm.value.resetFields()
  }
}


// 用户头像显示
const handleAvatarSuccess = (
  response
) => {
  empForm.value.image = response.data
}

// 用户头像校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('该图片不是JPG类型!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }
  return true
}

// 添加工作经历
const handleAddWork = () => {
  empForm.value.exprList.push({
    company: '',
    job: '',
    begin: '',
    end: '',
    date: []
  })
}

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});

// 删除工作经历
const handleDeleteWork = (index) => {
  empForm.value.exprList.splice(index, 1)
}

// 添加监听
watch(() => empForm.value.exprList, () => {
  empForm.value.exprList.forEach((item) => {
    item.begin = item.date[0]
    item.end = item.date[1]
  })
}, { deep: true })

// 保存按钮
const submitForm = async () => {
  if (!ruleEmpForm) return
  await ruleEmpForm.value.validate(async (valid, fields) => {
    if (valid) {
      let result = null
      if (empForm.value.id) {
        result = await updateEmpByIdApi(empForm.value)
        if (result.code) {
          ElMessage.success("修改员工成功！")
          dialogFormVisible.value = false
          query()
        } else {
          ElMessage.error("修改员工失败！")
        }
      } else {
        result = await addEmpApi(empForm.value)
        if (result.code) {
          ElMessage.success("添加员工成功！")
          dialogFormVisible.value = false
          query()
        } else {
          ElMessage.error("添加员工失败！")
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 取消按钮
const visible = () => {
  if (ruleEmpForm.value) {
    ruleEmpForm.value.resetFields()
  }
  dialogFormVisible.value = false
}

// 定义批量删除的员工id
const ids = ref(null)
// 表格批量删除
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}
// 批量删除按钮
const deleteIds = async () => {
  const result = await deleteEmpByIdsApi(ids.value)
  if (result.code) {
    ElMessage.success("删除成功！")
  } else {
    ElMessage.error("删除失败！")
  }
}
</script>

<template>
  <p>员工管理</p>
  <!-- el-form表单 -->
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="formInline.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="formInline.gender" placeholder="请选择" clearable style="width: 120px;">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职时间">
      <el-date-picker v-model="formInline.date" type="daterange" range-separator="至" start-placeholder="开始时间"
        end-placeholder="结束时间" size="default" value-format="YYYY-MM-DD" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="query">查询</el-button>
      <el-button @click="clear">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 新增员工按钮 -->
  <el-button type="primary" @click="add">新增员工</el-button>
  <el-button type="danger" @click="deleteIds">批量删除</el-button>
  <br><br>

  <!-- 新增员工按钮对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="800">
    <el-form :model="empForm" label-width="80px" :rules="rules" ref="ruleEmpForm">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="empForm.username" placeholder="请输入员工用户名,2-20个字" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="empForm.name" placeholder="请输入员工姓名,2-10个字" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
            <el-select v-model="empForm.gender" placeholder="请选择">
              <el-option v-for="(item,index) in genderOptions" :key="index" :label="item.gender" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="empForm.phone" placeholder="请输入员工手机号" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="empForm.job" placeholder="请选择">
              <el-option v-for="(item,index) in jobOptions" :key="index" :label="item.job" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="empForm.salary" placeholder="请输入员工薪资" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="empForm.deptId" placeholder="请选择">
              <el-option v-for="(item,index) in deptOptions" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="empForm.entryDate" type="date" placeholder="请选择入职日期" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="头像">
        <el-upload class="avatar-uploader" :headers="token" action="/api/upload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="empForm.image" :src="empForm.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="工作经历">
        <el-button type="success" @click="handleAddWork">添加工作经历</el-button>
        <br><br>
        <el-row :gutter="3" v-for="(item,index) in empForm.exprList" :key="index">
          <br><br>
          <el-col :span="10">
            <el-form-item label="时间" label-width="40px">
              <el-date-picker v-model="item.date" type="daterange" range-separator="到" start-placeholder="开始日期"
                end-placeholder="结束日期" size="default" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公司" label-width="40px">
              <el-input v-model="item.company" placeholder="请输入公司的名字" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位" label-width="40px">
              <el-input v-model="item.job" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="danger" @click="handleDeleteWork(index)">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="visible()">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 表格 -->
  <el-table :data="empData" style="width: 100%" width="auto" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column label="性别">
      <template #default="scope">
        <span>{{ scope.row.gender == 1 ? '男' : '女' }}</span>
      </template>
    </el-table-column>
    <el-table-column label="头像">
      <template #default="scope">
        <el-image style="width: 50px; height: 50px" :src="scope.row.image" />
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" />
    <el-table-column prop="job" label="职位">
      <template #default="scope">
        <span>{{ scope.row.job == 1 ? '班主任' : (scope.row.job == 2 ? '讲师' : (scope.row.job == 3 ? '学工主管' : (scope.row.job == 4 ? '教研主管' : (scope.row.job == 5 ? '咨询师' : '其他'))))}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="entryDate" label="入职日期" />
    <el-table-column prop="updateTime" label="最后操作时间" width="200px" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row.id)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
    :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
    :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style scoped>
.el-pagination {
  margin-top: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>